#!/usr/bin/python
# -*- coding: utf8 -*-

import re, codecs, os, sys
from pysqlite2 import dbapi2 as sqlite
from Site import Auth, Searcher, Messanger, Checker
from Database import Database

class Master(object):
   def __init__(self):
      self.db_cursor = 0
      self.connection = 0
      self.dbpath = './db/agsf.s3db'
      self.searcher = Searcher()
      self.auth      = None
      self.messanger = Messanger()
      self.checker   = Checker()

   def Authorize(self):
      if not self.auth:
         self.auth = Auth()
      self.auth.Retrieve('http://dating.ru/logout.php')
      self.auth.Login('ivankr', 'qwefgh')
      self.messanger.setAuth(self.auth)
      self.checker.setAuth(self.auth)

   def Append_daters(self, count = 10):
      cursor = self.Connect()
      daters = self.searcher.getDaters(count)
      for dater in daters:
         dater.Append(cursor)
      self.Apply()

   def Write_to_lonely(self, count, message):
      db     = Database()
      daters = db.getDaters(count)
      self.Authorize()
      for dater in daters:
         self.messanger.Send_message(dater.oid, message)
         self.messanger.Be_polite()

   def Connect(self):
      self.connection = sqlite.connect(self.dbpath)
      cursor = self.connection.cursor()
      return cursor

   def Apply(self):
      self.connection.commit()

   def onCommand(self, command):
      pass

   def onSearch(self, params):
      pass

   def onCheckConversations(self, user):
      pass

   def onSend(self, message):
      pass

def main():
   m = Master()
   #m.Authorize()
   m.Write_to_lonely(2, u'Привет! Правда, я красавец?'.encode('cp1251'))
   #m.Append_daters(100)

if __name__ == '__main__':
   main()